<?php
namespace app\controller;

use think\exception\ValidateException;
use think\Request;

class Login extends Base
{
    protected function initialize()
    {
        parent::initialize();
        $this->logic = new \app\logic\User;
    }

    /**
     * 登录
     */
    public function index()
    {
        // 判断是否登录
        if($this->logic->isLogin()) {
            return redirect((string) url('Index/index'));
        }
        if(request()->isAjax()) {
            $params = request()->param(['username', 'password', 'captcha', 'remember'], [], 'trim');
            if(empty($params)) {
                return $this->jsonReturn(config('status.request'), '参数错误');
            }
            // 验证登录数据
            try {
                validate(\app\validate\User::class)->scene('login')->check($params);
            } catch(ValidateException $e) {
                return $this->jsonReturn(config('status.verify'), $e->getError());
            }
            // 执行登录
            return $this->jsonReturn($this->logic->login($params));
        }
        return view();
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        return $this->jsonReturn($this->logic->logout());
    }
}